﻿/*
* 特殊方法
*
*/

// 缓存
var iss_sessionStorage = {
    set: function (key, value) {
        sessionStorage.removeItem(key);
        sessionStorage[key] = value;
    },
    get: function (key) {
        return sessionStorage.getItem(key) ? sessionStorage.getItem(key) : "";
    },
    getJson: function (key) {
        var str = sessionStorage.getItem(key);
        var obj = $.parseJSON(str);
        return obj;
    },
    remove: function (key) {
        sessionStorage.removeItem(key);
    },
    clear: function () {
        sessionStorage.clear();
    }
};

/*
* 动态加载Js or Css
*/
var dynamicLoading = {
    icon: function (path) {
        if (!path || path.length === 0) {
            throw new Error('argument "path" is required !');
        }
        var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.href = path;
        link.rel = 'shortcut icon';
        head.appendChild(link);
    },
    css: function (path) {
        if (!path || path.length === 0) {
            throw new Error('argument "path" is required !');
        }
        var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.href = path;
        link.rel = 'stylesheet';
        link.type = 'text/css';
        head.appendChild(link);
    },
    js: function (path) {
        if (!path || path.length === 0) {
            throw new Error('argument "path" is required !');
        }
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.src = path;
        script.type = 'text/javascript';
        head.appendChild(script);
    }
}

/*
* 没有图片
*/
function NoPicture() {
    var url = "../../assets/images/base/noPicture.jpg";
    return url;
};

/* 工具类 */

/**
* 创建ISS命名空间，ISS提供的内容都在此空间下
*/
var ISS = {
    version: '1.0'
};
/**
* ------------------工具集合-------------------
*/
ISS.utils = {

};
/**
* 获取当前url中的属性值
* 
* @param property 属性名称
* @returns 返回具体属性对应的值，如果没有则返回空字符串
*/
ISS.utils.getParameter = function (property) {
    var LocString = String(window.document.location.href);
    var rs = new RegExp("(^|)" + property + "=([^\&]*)(\&|$)", "gi")
        .exec(LocString), tmp;
    if (tmp = rs) {
        return tmp[2];
    }
    return "";
};
//字符串截取工具
ISS.utils.subString = function (property) {

    var LocString = String(property).substring(0, 5);
    return LocString;

};
//小数位
ISS.utils.toFixed = function (property, len) {

    var LocNum = 0;
    if (!isNaN(property) && property != 0) {
        LocNum = new Number(property);
        LocNum = LocNum.toFixed(2);
    }
    return LocNum;

};

/**
* 日期对象转换为指定格式的字符串
* @param f 日期格式,格式定义如下 yyyy-MM-dd HH:mm:ss
* @param date Date日期对象, 如果缺省，则为当前时间
*
* YYYY/yyyy/YY/yy 表示年份  
* MM/M 月份  
* W/w 星期  
* dd/DD/d/D 日期  
* hh/HH/h/H 时间  
* mm/m 分钟  
* ss/SS/s/S 秒  
* @return string 指定格式的时间字符串
*/
ISS.utils.dateToStr = function (formatStr, date) {
    formatStr = arguments[0] || "yyyy-MM-dd HH:mm:ss";
    date = arguments[1] || new Date();
    var str = formatStr;
    var Week = ['日', '一', '二', '三', '四', '五', '六'];
    str = str.replace(/yyyy|YYYY/, date.getFullYear());
    str = str.replace(/yy|YY/, (date.getYear() % 100) > 9 ? (date.getYear() % 100).toString() : '0' + (date.getYear() % 100));
    str = str.replace(/MM/, date.getMonth() >= 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1));
    str = str.replace(/M/g, date.getMonth());
    str = str.replace(/w|W/g, Week[date.getDay()]);

    str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate());
    str = str.replace(/d|D/g, date.getDate());

    str = str.replace(/hh|HH/, date.getHours() > 9 ? date.getHours().toString() : '0' + date.getHours());
    str = str.replace(/h|H/g, date.getHours());
    str = str.replace(/mm/, date.getMinutes() > 9 ? date.getMinutes().toString() : '0' + date.getMinutes());
    str = str.replace(/m/g, date.getMinutes());

    str = str.replace(/ss|SS/, date.getSeconds() > 9 ? date.getSeconds().toString() : '0' + date.getSeconds());
    str = str.replace(/s|S/g, date.getSeconds());

    return str;
}
/**
* 字符串转换为日期对象
* @param date Date 格式为yyyy-MM-dd HH:mm:ss，必须按年月日时分秒的顺序，中间分隔符不限制
*/
ISS.utils.strToDate = function (dateStr) {
    var data = dateStr;
    var reCat = /(\d{1,4})/gm;
    var t = data.match(reCat);
    t[1] = t[1] - 1;
    eval('var d = new Date(' + t.join(',') + ');');
    return d;
};
/**
* 日期计算  
* @param strInterval string  可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒  
* @param num int
* @param date Date 日期对象
* @return Date 返回日期对象
*/
ISS.utils.dateAdd = function (strInterval, num, date) {
    date = arguments[2] || new Date();
    switch (strInterval) {
        case 's': return new Date(date.getTime() + (1000 * num));
        case 'n': return new Date(date.getTime() + (60000 * num));
        case 'h': return new Date(date.getTime() + (3600000 * num));
        case 'd': return new Date(date.getTime() + (86400000 * num));
        case 'w': return new Date(date.getTime() + ((86400000 * 7) * num));
        case 'm': return new Date(date.getFullYear(), (date.getMonth()) + num, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
        case 'y': return new Date((date.getFullYear() + num), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
    }
}

var iss_localStorage = {
    set: function (key, value) {
        localStorage.removeItem(key);
        localStorage.setItem(key, value);
    },
    get: function (key) {
        return localStorage.getItem(key) ? localStorage.getItem(key) : "";
    },
    getJson: function (key) {
        var str = localStorage.getItem(key);
        var obj = $.parseJSON(str);
        return obj;
    },
    remove: function (key) {
        localStorage.removeItem(key);
    },
    clear: function () {
        localStorage.clear();
    }
};
/*
*获取指定位数的随机数
*
*/
ISS.utils.generateMixed = function (n) {
    var res = "";
    for (var i = 0; i < n; i++) {
        var id = Math.floor(Math.random() * 10);
        res += _charscode[id];
    }
    return res;

};
/**
 * 在一个区间内随机生成一个整数，
 */
ISS.utils.randomInt = function (min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}
/*
*获取指定日期，上个月的日期
*
*/
ISS.utils.getUpMonth = function (t) {
    var tarr = t.split('-');
    var year = tarr[0];                //获取当前日期的年
    var month = tarr[1];            //获取当前日期的月
    var day = tarr[2];                //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中的月的天数

    var year2 = year;
    var month2 = parseInt(month) - 1;
    if (month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }

    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
};
/*
*获取指定日期，昨天的日期
*
*/
ISS.utils.getYestoday = function (date) {
    var yesterday_milliseconds = date.getTime() - 1000 * 60 * 60 * 24;
    var yesterday = new Date();
    yesterday.setTime(yesterday_milliseconds);

    var strYear = yesterday.getFullYear();
    var strDay = yesterday.getDate();
    var strMonth = yesterday.getMonth() + 1;
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    datastr = strYear + "-" + strMonth + "-" + strDay;
    return datastr;
};
/*
*获取指定日期，上一年的日期
*
*/
ISS.utils.getLastYearYestdy = function (date) {
    var strYear = date.getFullYear() - 1;
    var strDay = date.getDate();
    var strMonth = date.getMonth() + 1;
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    if (strDay < 10) {
        strDay = "0" + strDay;
    }
    datastr = strYear + "-" + strMonth + "-" + strDay;
    return datastr;
};

/*
*初始化定位
*
*/
ISS.utils.initLocation = function () {
    ISS.utils.onDeviceReady();

};
ISS.utils.unLoadLocation = function () {
    navigator.geolocation.clearWatch(watchId);
};
ISS.utils.onDeviceReady = function () {
    //单次定位使用GPS高精度模式
    //navigator.geolocation.getCurrentPosition(ISS.utils.onSuccess, ISS.utils.onError, { frequency: 1000, enableHighAccuracy: true });
};
ISS.utils.onSuccess = function (position) {
    //获取用户当前经纬度
    //ISS_Constants.User.longitude = position.coords.longitude;
    //ISS_Constants.User.latitude = position.coords.latitude;
    iss_localStorage.set("yuqing_longitude", position.coords.longitude);
    iss_localStorage.set("yuqing_latitude", position.coords.latitude);
};
ISS.utils.onError = function (error) {
    if (error.code == 1) {
        myApp.alert("您拒绝了使用位置服务,将会影响部分功能。")
    }
};
ISS.utils.initLocation = function (fun) {
    try {
        // var map = new BMap.Map("allmap");
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function (r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                //ISS_Constants.User.longitude = position.coords.longitude;
                //ISS_Constants.User.latitude = position.coords.latitude;
                iss_localStorage.set("yuqing_longitude", r.point.lng);
                iss_localStorage.set("yuqing_latitude", r.point.lat);
                iss_localStorage.set("yuqing_location_time", new Date().getTime());
                var url = 'http://api.map.baidu.com/geocoder/v2/?ak=P6VrB5UEVvbu1wifaYtlMF2BDpgG13oX&callback=?&location=' + r.point.lat + ',' + r.point.lng + '&output=json&pois=1';
                $.getJSON(url, function (res) {
                    iss_localStorage.set("yuqing_current_address",res.result.formatted_address);
                });
                if (typeof (fun) != "undefined") {
                    fun();
                }
            }
            else {
                alert('failed' + this.getStatus());
            }
        }, { enableHighAccuracy: true })

    } catch (e) {

    }
}
//日期运算
Date.prototype.DateAdd = function (date, strInterval, Number) {
    var dtTmp = date;
    switch (strInterval) {
        case 's': return new Date(Date.parse(dtTmp) + (1000 * Number));
        case 'n': return new Date(Date.parse(dtTmp) + (60000 * Number));
        case 'h': return new Date(Date.parse(dtTmp) + (3600000 * Number));
        case 'd': return new Date(Date.parse(dtTmp) + (86400000 * Number));
        case 'w': return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
        case 'q': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case 'm': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case 'y': return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    }
}

//日期格式化
function GetDate(myDate) {
    var ynow = myDate.getFullYear();
    var mnow = myDate.getMonth() + 1;
    var dnow = myDate.getDate();
    if (mnow.toString().length == "1") {
        return ynow + "-0" + mnow + "-" + dnow;
    }
    else {
        return ynow + "-" + mnow + "-" + dnow;
    }
}
//日期比较
function CheckDoubleDate(date1, date2) {
    var arr = date1.split("-");
    var starttime = new Date(arr[0], arr[1], arr[2]);
    //var starttimes = starttime.getTime();

    var arrs = date2.split("-");
    var lktime = new Date(arrs[0], arrs[1], arrs[2]);

    var cha = ((Date.parse(arr[1] + '/' + arr[2] + '/' + arr[0]) - Date.parse(arrs[1] + '/' + arrs[2] + '/' + arrs[0])) / 86400000);
    if (cha > 0) {
        return false;
    }
    else {
        return true;
    }
}

///当前日期
function GetDateStr(AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1; //获取当前月份的日期
    var d = dd.getDate();
    return new Date(y + "-" + m + "-" + d);
}

//当前日期  字符
function GetDateFormatString(AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1; //获取当前月份的日期
    var d = dd.getDate();
    return y + "-" + m + "-" + d;
}


//日历控件
function DatepickerFun(txtID) {
    var dayNames = ['星期一', '星期一', '星期一', '星期一', '星期一', '星期一', '星期一']
    var monthNames = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
    var calendarInline = myApp.calendar({
        input: txtID,
        cssClass: "theme-red",
        closeOnSelect: true,
        //dateFormat: 'DD, MM dd, yyyy',
        dateFormat: 'yyyy-mm-dd',
        value: [new Date()],
        minDate: GetDateStr(0),
        weekHeader: true,
        dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
        toolbarTemplate:
        '<div class="toolbar calendar-custom-toolbar">' +
        '<div class="toolbar-inner">' +
        '<div class="left">' +
        '<a href="#" class="link icon-only"><i class="icon icon-back"></i></a>' +
        '</div>' +
        '<div class="center"></div>' +
        '<div class="right">' +
        '<a href="#" class="link icon-only"><i class="icon icon-forward"></i></a>' +
        '</div>' +
        '</div>' +
        '</div>',
        onOpen: function (p) {
            $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth] + "月");
            $$('.calendar-custom-toolbar .left .link').on('click', function () {
                calendarInline.prevMonth();
            });
            $$('.calendar-custom-toolbar .right .link').on('click', function () {
                calendarInline.nextMonth();
            });
        },
        onMonthYearChangeStart: function (p) {
            $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth] + "月");
        }
    });
}
//日历控件
function DatepickerFunXianLu(txtID, onClose) {
    var dayNames = ['星期一', '星期一', '星期一', '星期一', '星期一', '星期一', '星期一']
    var monthNames = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
    var calendarInline = myApp.calendar({
        input: txtID,
        cssClass: "theme-red",
        closeOnSelect: true,
        //dateFormat: 'DD, MM dd, yyyy',
        dateFormat: 'yyyy-mm-dd',
        value: GetDateStr(5),
        minDate: GetDateStr(5),
        weekHeader: true,
        dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
        toolbarTemplate:
        '<div class="toolbar calendar-custom-toolbar">' +
        '<div class="toolbar-inner">' +
        '<div class="left">' +
        '<a href="#" class="link icon-only"><i class="icon icon-back"></i></a>' +
        '</div>' +
        '<div class="center"></div>' +
        '<div class="right">' +
        '<a href="#" class="link icon-only"><i class="icon icon-forward"></i></a>' +
        '</div>' +
        '</div>' +
        '</div>',
        onOpen: function (p) {
            $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth] + "月");
            $$('.calendar-custom-toolbar .left .link').on('click', function () {
                calendarInline.prevMonth();
            });
            $$('.calendar-custom-toolbar .right .link').on('click', function () {
                calendarInline.nextMonth();
            });
        },
        onClose: onClose,
        onMonthYearChangeStart: function (p) {
            $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth] + "月");
        }
    });
}
//日历控件
function DatepickerFunHotel(txtID, Zq, onClose) {
    var dayNames = ['星期一', '星期一', '星期一', '星期一', '星期一', '星期一', '星期一']
    var monthNames = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
    var calendarInline = myApp.calendar({
        input: txtID,
        cssClass: "theme-red",
        closeOnSelect: true,
        //dateFormat: 'DD, MM dd, yyyy',
        dateFormat: 'yyyy-mm-dd',
        value: GetDateStr(parseInt(Zq)),
        minDate: GetDateStr(parseInt(Zq)),
        weekHeader: true,
        dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
        toolbarTemplate:
        '<div class="toolbar calendar-custom-toolbar">' +
        '<div class="toolbar-inner">' +
        '<div class="left">' +
        '<a href="#" class="link icon-only"><i class="icon icon-back"></i></a>' +
        '</div>' +
        '<div class="center"></div>' +
        '<div class="right">' +
        '<a href="#" class="link icon-only"><i class="icon icon-forward"></i></a>' +
        '</div>' +
        '</div>' +
        '</div>',
        onOpen: function (p) {
            $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth] + "月");
            $$('.calendar-custom-toolbar .left .link').on('click', function () {
                calendarInline.prevMonth();
            });
            $$('.calendar-custom-toolbar .right .link').on('click', function () {
                calendarInline.nextMonth();
            });
        },
        onClose: onClose,
        onMonthYearChangeStart: function (p) {
            $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth] + "月");
        }
    });
}
//是否在微信的浏览器下
ISS.utils.isWeiXin = function () {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
}

//将string格式的时间，去掉时分秒
//在IE下new Date(datetime)，如果datetime带了时分秒会报错
ISS.utils.ReplaceHMS = function (datetime) {
    var dts = [];
    dts = datetime.split(' ');
    if (dts.length > 0) {
        return dts[0];
    }
    else {
        return datetime;
    }
}

//给string重载方法startWith和endWith
String.prototype.startWith = function (str) {
    var reg = new RegExp("^" + str);
    return reg.test(this);
}

String.prototype.endWith = function (str) {
    var reg = new RegExp(str + "$");
    return reg.test(this);
}

//手机号码验证
ISS.utils.CheckPhone = function (phoneNumber) {
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    if (!myreg.test(phoneNumber)) {
        return false;
    } else {
        return true;
    }
}

String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题，谢谢何以笙箫的指出
                    var reg = new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

//生成GUID
ISS.utils.GUID = function newGuid() {
    var guid = "";
    for (var i = 1; i <= 32; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;
    }
    return guid;
}

String.prototype.startWith = function (str) {
    var reg = new RegExp("^" + str);
    return reg.test(this);
}

String.prototype.endWith = function (str) {
    var reg = new RegExp(str + "$");
    return reg.test(this);
}